package com.zhuqi.message.config;

import com.zhuqi.message.listener.Subscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>类描述</p>
 * Copyright: Copyright (C) 2023 YinTa, Inc. All rights reserved.
 * @author zhuqi
 * @since 2023/4/13 9:47
 */
@Configuration
public class MessageConfig {
	@Autowired
	private Subscriber subscriber;

	/**
	 * 配置 RedisMessageListenerContainer 监听器容器
	 * @param connectionFactory 连接工厂
	 * @param listenerAdapter 消息侦听器适配器
	 * @return
	 */
	@Bean
	public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
			MessageListenerAdapter listenerAdapter) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		// 消息主题列表
		List<Topic> topicList = new ArrayList<>();
		// 订阅 “hxstrive” 频道
		topicList.add(new ChannelTopic("chat"));
		// 订阅 “*.hxstrive.com” 模式
		topicList.add(new PatternTopic("*.chat.com"));
		// 将消息侦听器添加到容器中
		container.addMessageListener(listenerAdapter, topicList);
		return container;
	}

	/**
	 * 消息侦听器适配器，能将消息委托给目标侦听器
	 * @return
	 */
	@Bean
	public MessageListenerAdapter listenerAdapter() {
		return new MessageListenerAdapter(subscriber);
	}

}
